package com.yutel.phone.binh.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import com.yutel.phone.binh.R;
import com.yutel.phone.binh.data.vo.VideoStream;
import com.yutel.phone.binh.service.PlayerService;
import com.yutel.phone.binh.service.ServiceReceiver;

public class PlayerActivity extends BaseActivity implements
		ServiceReceiver.Receiver, View.OnClickListener, SurfaceHolder.Callback {
	private static final String TAG = "PlayerActivity";
	private ServiceReceiver mReceiver;
	private SurfaceView surfaceView;
	private MediaPlayer mediaPlayer;
	private int videoIndex;
	private VideoStream vs;
	private View playerbar;
	private ImageButton btnStart;
	private ImageButton btnPause;
	private ImageButton btnStop;
	private ImageButton btnSave;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player_layout);
		mReceiver = new ServiceReceiver(new Handler());
		mReceiver.setReceiver(this);
		surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
		playerbar = (View) findViewById(R.id.playerbar);
		btnStart = (ImageButton) findViewById(R.id.btnstart);
		btnPause = (ImageButton) findViewById(R.id.btnpause);
		btnStop = (ImageButton) findViewById(R.id.btnstop);
		btnSave = (ImageButton) findViewById(R.id.btnsave);
		btnStart.setOnClickListener(this);
		btnPause.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnStart.setClickable(false);
		btnPause.setClickable(false);
		btnStop.setClickable(false);
		btnSave.setClickable(false);
		playerbar.setVisibility(View.VISIBLE);
		String url = getIntent().getStringExtra(Intent.EXTRA_TEXT);
		if (url != null && !"".equals(url)) {
			Intent intent = new Intent(Intent.ACTION_SYNC, null, this,
					PlayerService.class);
			intent.putExtra(PlayerService.EXTRA_STATUS_RECEIVER, mReceiver);
			intent.putExtra(Intent.EXTRA_TEXT, url);
			startService(intent);
		} else {
			finish();
		}
	}

	@Override
	protected void onResume() {
		if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
			mediaPlayer.start();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (mediaPlayer != null) {
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.stop();
			}
			mediaPlayer.release();
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		try {
			switch (v.getId()) {
			case R.id.btnstart:
				if (videoIndex < vs.getPlayUrl().size()) {
					mediaPlayer.reset();
					mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
					mediaPlayer.setDisplay(surfaceView.getHolder());
					mediaPlayer.setDataSource(vs.getPlayUrl().get(videoIndex));
					mediaPlayer.prepare();
					mediaPlayer.start();
				}
				break;
			case R.id.btnpause:
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.pause();
				} else {
					mediaPlayer.start();
				}
				break;
			case R.id.btnstop:
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.stop();
				}
				finish();
				break;
			case R.id.btnsave:
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.stop();
				}
				Log.i(TAG, "save!");
				saveFilem3u("test.m3u");
				break;
			}
		} catch (Exception e) {
			Log.e(TAG, "onclick();", e);
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.i(TAG, "surfaceCreated();");
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.i(TAG, "surfaceChanged();");
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.i(TAG, "surfaceDestroyed();");
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		Log.i(TAG, "onReceiveResult=" + resultCode);
		switch (resultCode) {
		case PlayerService.STATUS_RUNNING:

			break;
		case PlayerService.STATUS_FINISHED:
			ArrayList<VideoStream> mDataList = (ArrayList<VideoStream>) resultData
					.getSerializable(PlayerService.class.getSimpleName());
			if (mDataList != null && mDataList.size() > 0) {
				vs = mDataList.get(0);
				String url = vs.getPlayUrl().get(0);
				try {
					mediaPlayer = new MediaPlayer();
					mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
						@Override
						public void onCompletion(MediaPlayer mp) {
							Log.i(TAG, "onCompletion();");
						}
					});
					mediaPlayer.reset();
					mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
					mediaPlayer.setDisplay(surfaceView.getHolder());
					mediaPlayer.setDataSource(url);
					mediaPlayer.prepare();
					mediaPlayer.start();
				} catch (Exception e) {
					Log.e(TAG, "onclick();", e);
				}
				btnStart.setClickable(true);
				btnPause.setClickable(true);
				btnStop.setClickable(true);
				btnSave.setClickable(true);
			}

			break;
		default:
			Log.w(TAG, "warring resultCode=" + resultCode);
		}
	}
	/** save file
	 * 
	 * @param filename
	 */
	private void saveFilem3u(String filename) {
		if (vs != null) {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				FileOutputStream fos = null;
				try {
					File sd = Environment.getExternalStorageDirectory();
					File path = new File(sd.getPath() + "/bhfile");
					if (!path.exists()) {
						path.mkdir();
					}
					File file = new File(path.getPath() + File.separator
							+ filename);
					fos = new FileOutputStream(file);
					StringBuffer sb = new StringBuffer();
					for (String item : vs.getPlayUrl()) {
						sb.append(item).append("\n");
					}
					fos.write(sb.toString().getBytes());
					Log.i(TAG, "save to sdcard:bhfile");
					Toast.makeText(this, "no sdcard!", Toast.LENGTH_SHORT);
				} catch (Exception e) {
					Log.e(TAG, "saveM3uFile error!", e);
				} finally {
					try {
						fos.close();
					} catch (IOException e) {
						Log.e(TAG, "fos.close error!", e);
					}
				}
			} else {
				Log.e(TAG, "no sdcard!");
				Toast.makeText(this, "no sdcard!", Toast.LENGTH_SHORT);
			}
		}
	}
}
